﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class DBHelper
    {
        //数据库链接字符串
        public static string ConnString = "server=.;database=Tao;Integrated Security=True;";
        //数据库链接对象
        public static SqlConnection Conn;
        //初始化数据库链接
        public static void Init()
        {
            if (Conn == null)
            {
                Conn = new SqlConnection(ConnString);
            }
            if (Conn.State == ConnectionState.Closed)
            {
                Conn.Open();
            }
            if (Conn.State == ConnectionState.Broken)
            {
                Conn.Close();
                Conn.Open();
            }
        }
        //获取DataTable 断开
        public static DataTable GetDataTable(string Str)
        {
            Init();
            SqlDataAdapter da = new SqlDataAdapter(Str, Conn);
            DataTable dt = new DataTable();
            da.Fill(dt);
            return dt;
        }
        //获取DataSet 断开
        public static DataSet GetDataSet(string Str)
        {
            Init();
            SqlDataAdapter dd = new SqlDataAdapter(Str, Conn);
            DataSet ds = new DataSet();
            dd.Fill(ds);
            return ds;
        }
        //获取DataReader 非断开
        public static SqlDataReader GetDataReader(string Str)
        {
            Init();
            SqlCommand cmd = new SqlCommand(Str, Conn);
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }
        //增 删 改
        public static bool ExecuteNonQuery(string Str)
        {
            Init();
            SqlCommand cmd = new SqlCommand(Str, Conn);
            int r = cmd.ExecuteNonQuery();
            return r > 0;
        }
        //聚合函数
        public static object ExecuteScalar(string Str)
        {
            Init();
            SqlCommand cmd = new SqlCommand(Str, Conn);
            object r = cmd.ExecuteScalar();
            return r;
        }
    }
}
